package com.mhxy.util;

import cn.hutool.core.io.FileUtil;
import com.mhxy.handler.ConfigHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;
import java.security.ProtectionDomain;

@Slf4j
public class DirUtil {

    /**
     * 临时截图目录
     */
    public static String TEMP_PIC_PATH = System.getProperty("user.dir") + File.separator + "otherResources" + File.separator + "tempPicDir" + File.separator;

    /**
     * 获取 JAR 文件所在的目录
     * @return
     */
    public static String getJarDirectory() {
        try {
            ProtectionDomain protectionDomain = DirUtil.class.getProtectionDomain();
            CodeSource codeSource = protectionDomain.getCodeSource();
            URL jarUrl = codeSource.getLocation();
            File jarFile = new File(jarUrl.toURI());
            return jarFile.getParent(); // 返回 JAR 文件所在的目录
        } catch (Exception e) {
            throw new RuntimeException("Failed to get JAR directory", e);
        }
    }

    public static String getGamePicPath() {
        if ("prod".equals(ConfigHandler.getProfiles())) {
            return System.getProperty("user.dir") +
                    File.separator + "mhxy-app-jar-with-dependencies.jar!" +
                    File.separator + "gamePic" + File.separator;
        }

        return System.getProperty("user.dir") +
                File.separator + "otherResources" +
                File.separator + "gamePic" + File.separator;
    }

    /**
     * 初始化文件夹参数
     */
    public static void initTempPicPath() {
        // 初始化文件夹
        File file = new File(TEMP_PIC_PATH);
        if (file.exists()) {
            boolean del = FileUtil.del(file);
            System.out.println("清空文件夹：" + del);
        }
        file.mkdirs();
    }

    public static void createTempDir() {
        try {
            // 创建临时目录
            Path tempDir = Files.createTempDirectory("tempPicDir");
            // 设置文件夹权限（可选）
            tempDir.toFile().setWritable(true, true); // 确保文件夹可写
            tempDir.toFile().setReadable(true, true); // 确保文件夹可读

            TEMP_PIC_PATH = tempDir + File.separator;
            log.info("创建临时文件夹: {}", TEMP_PIC_PATH);

            // 写入文件
//            Path tempFile = tempDir.resolve("output.txt");
//            Files.write(tempFile, "Hello, World!".getBytes());
//            System.out.println("File written to: " + tempFile);

            // 读取文件
//            byte[] data = Files.readAllBytes(tempFile);
//            System.out.println("File content: " + new String(data));
        } catch (IOException e) {
            throw new RuntimeException("创建临时文件夹失败！");
        }
    }
}
